'use strict';

const Controller = require('egg').Controller;
class SpecController extends Controller {
  async addSpec() {
    // 添加型号
    const { ctx } = this;
    try {
      ctx.validate({
        name: { type: 'string', required: true },
      }, ctx.request.body);
    } catch (err) {
      ctx.logger.error('addCategory err:', err);
      ctx.body = {
        code: -1,
        msg: '请求参数错误',
      };
      ctx.status = 400;
    }
    const data = ctx.request.body;
    const res = await this.service.specification.addSpec(data);
    if (res.code === 0) {
      ctx.body = {
        code: 0,
        msg: '新增成功',
      };
    } else {
      ctx.body = {
        code: -1,
        msg: JSON.stringify(res) || '新增失败',
      };
    }
  }
  async getSpecList() {
    // 获取型号列表
    const { ctx } = this;
    const res = await this.service.specification.getSpecList();
    if (res) {
      ctx.body = {
        code: 0,
        data: res,
      };
      ctx.status = 200;
    } else {
      ctx.body = {
        code: -1,
        msg: '获取商品型号失败',
      };
      ctx.status = 500;
    }
  }

  // 根据id获取型号信息
  async getSpecById() {
    const { ctx } = this;
    const id = ctx.query.id;
    const res = await this.service.specification.getSpecById(id);
    if (res) {
      ctx.body = {
        code: 0,
        data: res,
      };
      ctx.status = 200;
    } else {
      ctx.body = {
        code: -1,
        msg: '获取商品型号失败',
      };
      ctx.status = 500;
    }
  }

  // 根据id更新型号信息
  async updateSpec() {
    const { ctx } = this;
    const data = ctx.request.body;
    const res = await this.service.specification.updateSpec(data);
    if (res.code === 0) {
      ctx.body = {
        code: 0,
        msg: '更新型号成功',
      };
      ctx.status = 200;
    } else {
      ctx.body = {
        code: -1,
        msg: '更新型号失败',
      };
      ctx.status = 500;
    }
  }
  // 删除型号
  async deleteSpecById() {
    const { ctx } = this;
    const data = ctx.request.body;
    const res = await this.service.specification.deleteSpecById(data);
    if (res.code === 0) {
      ctx.body = {
        code: 0,
        msg: '删除型号成功',
      };
      ctx.status = 200;
    } else {
      ctx.body = {
        code: -1,
        msg: '删除型号失败',
      };
      ctx.status = 500;
    }
  }
}
module.exports = SpecController;
